package com.estar.app.business.mobileLogin.utils;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.tag.vo.datatable.SortDirection;
import org.jeecgframework.web.system.service.SystemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.estar.app.appsrvyyabx.mobile.domain.DataVO;
import com.estar.app.appsrvyyabx.mobile.domain.vo.WorkTimeVO;
import com.estar.app.business.common.service.AppService;
import com.estar.app.business.mobileLogin.entity.AppUserEntity;
import com.estar.platform.caseInfo.entity.TmblPicInfoEntity;
import com.estar.workparent.entity.TmblWorktimeParentEntity;
import com.estar.workplace.entity.TmblWorkPlaceEntity;
import com.estar.worktime.entity.TmblWorktimeEntity;

@Component("dutyUtil")
@Scope("prototype")
public class DutyUtil {
	@Autowired
	private SystemService systemService;
	
	private static String onTime="08:00:00";
	private static String offTimeHighWay="22:00:00";
	//private static String offTimeCity="19:00:00";		
	
	private static final Logger logger = Logger.getLogger(DutyUtil.class);
	
	private DateFormat df=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	private DateFormat dt=new SimpleDateFormat("HH:mm:ss");
	private DateFormat dd=new SimpleDateFormat("yyyy-MM-dd");
	private DateFormat dmonth=new SimpleDateFormat("MM");
	private DateFormat ym=new SimpleDateFormat("yyyy-MM");
	public DataVO onDuty(DataVO dataVO){
		try{
			WorkTimeVO workTimeVO=(WorkTimeVO) dataVO.getList().get(0);
			if(StringUtil.isEmpty(workTimeVO.getWorkplace())){
				dataVO.setResultCde("0");
				dataVO.setMessage("请选择服务点！");
			}else{
				//TmblWorktimeEntity tw=new TmblWorktimeEntity();
				
				Date today=new Date();
				Date d2=dt.parse(dt.format(today));
				
				
				CriteriaQuery cq=new CriteriaQuery(TmblWorktimeEntity.class);
				cq.eq("empcdoe", workTimeVO.getEmpcde());
				cq.eq("workplace", workTimeVO.getWorkplace());
				cq.eq("workdate", dd.parse(dd.format(today)));
				cq.add();
				List<TmblWorktimeEntity> wl=systemService.getListByCriteriaQuery(cq, false);
				
				if(wl!=null && wl.size()>0){
					//TmblWorktimeEntity tw = wl.get(0);
					for(TmblWorktimeEntity tw :wl){
						if(tw.getOndutytime()==null){
							tw.setOndutytime(today);//上班时间
							Date d1=dt.parse(onTime);
							
							//比较有无迟到
							 long l=0;
							if(d1.getTime()>d2.getTime()){
							      l=(d1.getTime()-d2.getTime());
							      tw.setLateflage("f");//没有迟到
							}else if(d1.getTime()<d2.getTime()){
								  l=(d2.getTime()-d1.getTime());
								  
								  tw.setLateflage("t");//迟到
								  long day=l/(24*60*60*1000);
								 long hour=(l/(60*60*1000)-day*24);
								 long min=((l/(60*1000))-day*24*60-hour*60);
								 long s=(l/1000-day*24*60*60-hour*60*60-min*60);
								 String Latertime=hour+":"+min+":"+s;
								 tw.setLatetime(Latertime);//记录相差时间
							}else{
								tw.setLateflage("f");
							}
							tw.setOndutycard("t");
							systemService.updateEntitie(tw);
						
							 dataVO.setResultCde("1");
							 dataVO.setMessage("上班签到成功");
							 
						}else{
							dataVO.setResultCde("1");
							dataVO.setMessage("今天上班已经签到");
						}
					}
				}else{//上班替班
					TmblWorktimeEntity tw=new TmblWorktimeEntity();
					
					//没录排班表
					String sql1="select w.id from tmbl_worktime_parent w where w.DAY='"+ym.format(new Date())+"'";
					List<String> lis=this.systemService.findListbySql(sql1);
					if (lis.size()>0 && lis!=null) {
						tw.setParentId(lis.get(0));
					}else{
						TmblWorktimeParentEntity twp=new TmblWorktimeParentEntity();
						twp.setCreatedate(new Date());
						twp.setCreatename("系统");
						twp.setCreateUserName("admin");
						twp.setDay(ym.format(new Date()));
						twp.setArrangework(ym.format(new Date())+"的替班信息");
						this.systemService.save(twp);
						if(StringUtil.isNotEmpty(twp.getId())){
							tw.setParentId(twp.getId());
						}else{
							tw.setParentId("1");
						}
					}
					//看看替换谁的班
					CriteriaQuery cw = new CriteriaQuery(TmblWorktimeEntity.class);
					cw.eq("workplace", workTimeVO.getWorkplace());
					cw.eq("workdate", dd.parse(dd.format(today)));
					cw.add();
					List<TmblWorktimeEntity> wlss=systemService.getListByCriteriaQuery(cw, false);
					if(wlss!=null && wlss.size()>0){
						String names="";
						for(TmblWorktimeEntity w:wlss){
							names+=w.getEmpname()+",";
						}
						names.substring(0,names.length()-1);
						tw.setReplaceName(names);
					}else{
						tw.setReplaceName("组长延迟了排班");
					}
					
					//信息录入
					tw.setWorkplace(workTimeVO.getWorkplace());
					List<TmblWorkPlaceEntity> workPlaceList=this.systemService.findByProperty(TmblWorkPlaceEntity.class, "workplace", workTimeVO.getWorkplace());	
					tw.setWorkPlaceId(workPlaceList.get(0).getId());
					tw.setWorkdate(dd.parse(dd.format(today)));
					tw.setEmpcdoe(workTimeVO.getEmpcde());
					
					List<AppUserEntity> empList=this.systemService.findByProperty(AppUserEntity.class, "empCde", workTimeVO.getEmpcde());	
					tw.setEmpname(empList.get(0).getEmpName());
					tw.setCreateName("替班");
					tw.setCreateDate(new Date());
					tw.setState("3");
					if(tw.getOndutytime()==null){
						tw.setOndutytime(today);//上班时间
						Date d1=dt.parse(onTime);
						
						//比较有无迟到
						 long l=0;
						if(d1.getTime()>d2.getTime()){
						      l=(d1.getTime()-d2.getTime());
						      tw.setLateflage("f");//没有迟到
						}else if(d1.getTime()<d2.getTime()){
							  l=(d2.getTime()-d1.getTime());
							  
							  tw.setLateflage("t");//迟到
							  long day=l/(24*60*60*1000);
							 long hour=(l/(60*60*1000)-day*24);
							 long min=((l/(60*1000))-day*24*60-hour*60);
							 long s=(l/1000-day*24*60*60-hour*60*60-min*60);
							 String Latertime=hour+":"+min+":"+s;
							 tw.setLatetime(Latertime);//记录相差时间
						}else{
							tw.setLateflage("f");
						}
						tw.setOndutycard("t");
						systemService.save(tw);
						 
						 dataVO.setResultCde("1");
						 dataVO.setMessage("上班签到成功");
						 
					}else {
						dataVO.setResultCde("1");
						dataVO.setMessage("今天上班已经签到");
					}
					
				}
			}
			dataVO.setList(null);
			
		}catch(Exception e){
			logger.error("签到功能系统异常：",e);
			dataVO.setResultCde("0");
			dataVO.setMessage("系统异常，签到失败");
		}
		
		return dataVO;
		
	}
	
	public DataVO offDuty(DataVO dataVO){
		try{
			WorkTimeVO workTimeVO=(WorkTimeVO) dataVO.getList().get(0);
			if(StringUtil.isEmpty(workTimeVO.getWorkplace())){
				dataVO.setResultCde("0");
				dataVO.setMessage("请选择服务点！");
			}else{
				//TmblWorktimeEntity tw=new TmblWorktimeEntity();
				
				Date today=new Date();
				Date d2=dt.parse(dt.format(today));
				
				CriteriaQuery cq=new CriteriaQuery(TmblWorktimeEntity.class);
				cq.eq("empcdoe", workTimeVO.getEmpcde());
				cq.eq("workplace", workTimeVO.getWorkplace());
				cq.eq("workdate", dd.parse(dd.format(today)));
				cq.add();
				List<TmblWorktimeEntity> wl=systemService.getListByCriteriaQuery(cq, false);
				
				if(wl!=null && wl.size()>0){
					
					//TmblWorktimeEntity tw=(TmblWorktimeEntity)wl.get(0);
					for(TmblWorktimeEntity tw:wl){
					   if(tw.getOffdutytime()==null){
						tw.setOffdutytime(today);//下班时间
						
						List<AppUserEntity> a=systemService.findByProperty(AppUserEntity.class, "empCde", tw.getEmpcdoe());
						Date d1=new Date();
						if(a.get(0).getArea().equals("2")){//城区和高速有不同的规定下班时间
							d1=dt.parse(offTimeHighWay);
						}else if(a.get(0).getArea().equals("1")){
							d1=dt.parse(chooseOffTime(dmonth.format(today)));
						}
						
						 long l=0;
						if(d1.getTime()>d2.getTime()){//判断有无早退
						     l=(d1.getTime()-d2.getTime());
							tw.setLeaveearlyflage("t");
							long day=l/(24*60*60*1000);
							 long hour=(l/(60*60*1000)-day*24);
							 long min=((l/(60*1000))-day*24*60-hour*60);
							 long s=(l/1000-day*24*60*60-hour*60*60-min*60);
							 String Leftearlytime=hour+":"+min+":"+s;
							 tw.setLeaveearlytime(Leftearlytime);//记录早退时间
						}else if(d1.getTime()<d2.getTime()){
							  l=(d2.getTime()-d1.getTime());
							tw.setLeaveearlyflage("f");
							
						}else{
							tw.setLeaveearlyflage("f");
						}
						 
						
						tw.setOffdutycard("t");
						systemService.updateEntitie(tw);
						
						
						 dataVO.setResultCde("1");
						 dataVO.setMessage("下班签到成功");
					   }else{
						   dataVO.setResultCde("1");
							dataVO.setMessage("今天已经下班签到");
					   }
					}
				}else{//替班下班没签到
					
					TmblWorktimeEntity tw=new TmblWorktimeEntity();
					
					//没录排班表
					String sql1="select w.id from tmbl_worktime_parent w where w.DAY='"+ym.format(new Date())+"'";
					List<String> lis=this.systemService.findListbySql(sql1);
					if (lis.size()>0 && lis!=null) {
						tw.setParentId(lis.get(0));
					}else{
						TmblWorktimeParentEntity twp=new TmblWorktimeParentEntity();
						twp.setCreatedate(new Date());
						twp.setCreatename("系统");
						twp.setCreateUserName("admin");
						twp.setDay(ym.format(new Date()));
						twp.setArrangework(ym.format(new Date())+"的替班信息");
						this.systemService.save(twp);
						if(StringUtil.isNotEmpty(twp.getId())){
							tw.setParentId(twp.getId());
						}else{
							tw.setParentId("1");
						}
					}
					
					//看替换了谁
					//看看替换谁的班
					CriteriaQuery cw = new CriteriaQuery(TmblWorktimeEntity.class);
					cw.eq("workplace", workTimeVO.getWorkplace());
					cw.eq("workdate", dd.parse(dd.format(today)));
					cw.add();
					List<TmblWorktimeEntity> wlss=systemService.getListByCriteriaQuery(cw, false);
					if(wlss!=null && wlss.size()>0){
						String names="";
						for(TmblWorktimeEntity w:wlss){
							names+=w.getEmpname()+",";
						}
						names.substring(0,names.length()-1);
						tw.setReplaceName(names);
					}else{
						tw.setReplaceName("组长延迟了排班");
					}
					
					tw.setWorkplace(workTimeVO.getWorkplace());
					
					List<TmblWorkPlaceEntity> workPlaceList=this.systemService.findByProperty(TmblWorkPlaceEntity.class, "workplace", workTimeVO.getWorkplace());	
					tw.setWorkPlaceId(workPlaceList.get(0).getId());
					
					tw.setWorkdate(dd.parse(dd.format(today)));
					tw.setEmpcdoe(workTimeVO.getEmpcde());
					
					List<AppUserEntity> empList=this.systemService.findByProperty(AppUserEntity.class, "empCde", workTimeVO.getEmpcde());	
					tw.setEmpname(empList.get(0).getEmpName());
					tw.setCreateName("替班");
					tw.setCreateDate(new Date());
					tw.setState("3");
					 if(tw.getOffdutytime()==null){
							tw.setOffdutytime(today);//下班时间
							
							List<AppUserEntity> a=systemService.findByProperty(AppUserEntity.class, "empCde", tw.getEmpcdoe());
							Date d1=new Date();
							if(a.get(0).getArea().equals("2")){//城区和高速有不同的规定下班时间
								d1=dt.parse(offTimeHighWay);
							}else if(a.get(0).getArea().equals("1")){
								d1=dt.parse(chooseOffTime(dmonth.format(today)));
							}
							
							 long l=0;
							if(d1.getTime()>d2.getTime()){//判断有无早退
							     l=(d1.getTime()-d2.getTime());
								tw.setLeaveearlyflage("t");
								long day=l/(24*60*60*1000);
								 long hour=(l/(60*60*1000)-day*24);
								 long min=((l/(60*1000))-day*24*60-hour*60);
								 long s=(l/1000-day*24*60*60-hour*60*60-min*60);
								 String Leftearlytime=hour+":"+min+":"+s;
								 tw.setLeaveearlytime(Leftearlytime);//记录早退时间
							}else if(d1.getTime()<d2.getTime()){
								  l=(d2.getTime()-d1.getTime());
								tw.setLeaveearlyflage("f");
								
							}else{
								tw.setLeaveearlyflage("f");
							}
							 
							 
							
							tw.setOffdutycard("t");
							systemService.save(tw);
							 dataVO.setResultCde("1");
							 dataVO.setMessage("下班签到成功");
						   }else{
							    dataVO.setResultCde("1");
								dataVO.setMessage("今天已经下班签到");
						   }
				}
			}
			
			dataVO.setList(null);
		}catch(Exception e){
			logger.error("签到功能系统异常：",e);
			dataVO.setResultCde("0");
			dataVO.setMessage("系统异常，签到失败");
		}
		
		return dataVO;
		
	}
	
	private String chooseOffTime(String m){
		String offTimeCity="19:00:00";
		if(m.equals("05") || m.equals("06") ||m.equals("07") ||m.equals("08") ||m.equals("09") ){
			offTimeCity="19:30:00";
		}
		return offTimeCity;
		
	}
	
}
